package com.demo.youxuanmall.config;

import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("拦截请求: {}, 请求方法: {}", requestURI, request.getMethod());
        
        // 不需要登录的路径
        if (isPublicPath(requestURI)) {
            log.debug("访问的是公共路径，允许通过");
            return true;
        }
        
        HttpSession session = request.getSession(false);
        log.info("Session是否存在: {}", session != null);
        
        if (session != null) {
            log.info("Session ID: {}", session.getId());
            User user = (User) session.getAttribute("user");
            log.info("Session中的用户信息: {}", user);
            
            if (user != null) {
                log.info("用户已登录: {}, 角色: {}", user.getUsername(), user.getRole());
                // 检查管理员权限
                if (requestURI.startsWith("/admin") && user.getRole() != 1) {
                    log.info("非管理员用户访问管理页面");
                    response.sendRedirect("/403");
                    return false;
                }
                return true;
            }
        }

        log.info("用户未登录，请求被拦截");
        // 判断是否是API请求
        if (requestURI.startsWith("/api/")) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write(objectMapper.writeValueAsString(Result.error("请先登录")));
        } else {
            // 普通页面请求重定向到登录页
            log.info("重定向到登录页");
            response.sendRedirect("/login");
        }
        return false;
    }

    private boolean isPublicPath(String requestURI) {
        // 列出所有不需要登录就能访问的路径
        return requestURI.equals("/") ||
               requestURI.equals("/login") ||
               requestURI.equals("/register") ||
               requestURI.equals("/api/login") ||
               requestURI.startsWith("/css/") ||
               requestURI.startsWith("/js/") ||
               requestURI.startsWith("/images/") ||
               requestURI.startsWith("/uploads/") ||
               requestURI.startsWith("/category") ||
               requestURI.startsWith("/product") ||
               requestURI.startsWith("/static/");
    }
} 